import sys

from deezer.api import Deezer
from deezer.streamer import stream
from deezer.quality import TrackQuality, FILE_FORMATS

def main():
    deezer = Deezer()

    def grab_track(song_id):
        track = deezer.get_track_data(int(song_id))
        data = track["results"]["DATA"]

        artists_string = ', '.join(map(lambda a: a["ART_NAME"], data["ARTISTS"]))
        print("grabbing {} by {}".format(data["SNG_TITLE"], artists_string))

        quality = TrackQuality.MP3_320
        file_format = FILE_FORMATS[quality]
        file_name = artists_string + ' - ' + data["SNG_TITLE"] + '.' + file_format

        with open(file_name, 'wb') as s:
            stream(s, track, TrackQuality.MP3_320, print)

    print('''
        Welcome to...
         _|_._ _ o  _ _|
        (_(/| | ||>(/(_|
    ''')
    if len(sys.argv) > 1:
        deezer.login_with_cookie(sys.argv[1])
        if len(sys.argv) > 2:
            grab_track(sys.argv[2])
    while True:
        command = input("-> ").split(" ")

        if command[0] == 'cookie':
            user = deezer.login_with_cookie(command[1])
            print("logged in as %s" % user["name"])
        elif command[0] == 'grab':
            grab_track(command[1])
        elif command[0] == 'exit':
            break
        else:
            print("unknown command... :/")
main()
